import {createRouter, createWebHashHistory} from 'vue-router'
import login from '@/view/login/index.vue'
import {useUserStore} from '@/pinia/modules/user'

const Router = [{
    path: '/', redirect: '/login'
}, {
    path: '/login', name: 'Login', component: login,
}, {
    path: '/dashboard',
    name: 'dashboard',
    component: () => import('@/view/layout/index.vue'),
    children: [{path: 'home', name: "首页", component: () => import('@/view/home/index.vue')}, {
        path: 'pipeline', name: "流水线", component: () => import('@/view/dashboard/pipeline/index.vue')
    }, {path: 'detail', name: "详情", component: () => import('@/view/detail/index.vue')}, {
        path: 'login', name: "登录", component: login
    },

        {path: 'envmanager', name: "环境", component: () => import('@/view/dashboard/env/envmanager.vue')}, {
            path: 'node', name: "节点", component: () => import('@/view/dashboard/env/node.vue')
        },

        //文章
        {
            path: 'article', name: "文章", component: () => import('@/view/dashboard/article/article.vue')
        }, {
            path: 'article/list',
            name: "文章列表",
            component: () => import('@/view/dashboard/article/articlelist.vue')
        }, {path: 'article/sheet', name: "sheet", component: () => import('@/view/dashboard/article/luckysheet.vue')},

        //用户
        {
            path: 'user',
            name: "用户管理",
            component: () => import('@/view/dashboard/user/user.vue'),
            props: {default: true}
        },

        // 用例管理
        {path: 'case', name: "用例管理", component: () => import('@/view/dashboard/case/case.vue')},

        // 接口测试
        {path: 'api', name: "接口测试", component: () => import('@/view/dashboard/resultful/index.vue')},]
},]

const router = createRouter({
    // history:createWebHashHistory(process.env.BASE_URL), //历史模式
    history: createWebHashHistory(), //hash 模式
    routes: Router
})

// 设置路由守卫，在进页面之前，判断有token，才进入页面，否则返回登录页面
router.beforeEach((to, from, next) => {
    var meaulist = window.localStorage.getItem('routers')
    if (meaulist != null) {
        meaulist = JSON.parse(meaulist)
        meaulist.forEach(item => {
            router.addRoute({
                path: item.path, name: item.name, component: () => import.meta.glob("../../view" + item.component)
            },)
        })
    }

    if (to.matched.some(r => r.meta.requireAuth) !== false) {
        let tokenInfo = useUserStore().token
        if (tokenInfo) {
            next();
        } else {
            next({
                path: "/login", query: {
                    redirect: to.fullPath
                } // 将刚刚要去的路由path（却无权限）作为参数，方便登录成功后直接跳转到该路由
            });
        }
    } else {
        next(); //如果无需token,那么随它去吧
    }
});

export default router
